package com.yuan.sys.modular.driver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuan.core.consts.CommonConstant;
import com.yuan.core.enums.CommonStatusEnum;
import com.yuan.core.exception.ServiceException;
import com.yuan.core.exception.enums.StatusExceptionEnum;
import com.yuan.core.factory.PageFactory;
import com.yuan.core.pojo.page.PageResult;
import com.yuan.core.util.PoiUtil;
import com.yuan.sys.modular.driver.entity.SysDriver;
import com.yuan.sys.modular.driver.enums.SysDriverExceptionEnum;
import com.yuan.sys.modular.driver.mapper.SysDriverMapper;
import com.yuan.sys.modular.driver.param.SysDriverParam;
import com.yuan.sys.modular.driver.result.SysDriverResult;
import com.yuan.sys.modular.driver.service.SysDriverService;
import com.yuan.sys.modular.user.entity.SysUser;
import com.yuan.sys.modular.user.enums.SysUserExceptionEnum;
import com.yuan.sys.modular.user.param.SysUserParam;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年10月21日 21:40
 */
@Service
public class SysDriverServiceImpl extends ServiceImpl<SysDriverMapper, SysDriver> implements SysDriverService {


    @Override
    public PageResult<SysDriverResult> page(SysDriverParam sysDriverParam) {
        QueryWrapper<SysDriverResult> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(sysDriverParam)) {
            //根据关键字模糊查询（姓名、工号、手机号）
            if (ObjectUtil.isNotEmpty(sysDriverParam.getSearchValue())) {
                queryWrapper.and(q -> q.like("sys_driver.employee_name", sysDriverParam.getSearchValue())
                        .or().like("sys_driver.employee_code", sysDriverParam.getSearchValue())
                        .or().like("sys_driver.phone", sysDriverParam.getSearchValue())
                );
            }
            //根据状态查询（1正常 0删除），删除的不会展示在列表
            if (ObjectUtil.isNotEmpty(sysDriverParam.getSearchStatus())) {
                queryWrapper.eq("sys_driver.status", sysDriverParam.getSearchStatus());
            }
            //排序
            if (ObjectUtil.isAllNotEmpty(sysDriverParam.getSortBy(), sysDriverParam.getOrderBy())) {
                queryWrapper.orderBy(true, sysDriverParam.getOrderBy().equals(CommonConstant.ASC), StrUtil.toUnderlineCase(sysDriverParam.getSortBy()));
            }
        }
        queryWrapper.ne("sys_driver.status", CommonStatusEnum.DELETED.getCode());
        return new PageResult<>(this.baseMapper.page(PageFactory.defaultPage(), queryWrapper));
    }


    @Override
    public void export(SysDriverParam sysDriverParam) {
        List<SysDriver> list = this.list();
        PoiUtil.exportExcelWithStream("Drivers.xls", SysDriver.class, list);
    }

    @Override
    public void delete(List<SysDriverParam> sysDriverParamList) {
        sysDriverParamList.forEach(sysDriverParam -> {
            SysDriver sysDriver = this.querySysDriver(sysDriverParam);
            sysDriver.setStatus(CommonStatusEnum.DELETED.getCode());
            this.updateById(sysDriver);
        });
    }

    @Override
    public void edit(SysDriverParam sysDriverParam) {
        SysDriver sysDriver = this.querySysDriver(sysDriverParam);
        checkIdCard(sysDriverParam, true);
        checkEmployeeCode(sysDriverParam, true);
        BeanUtil.copyProperties(sysDriverParam, sysDriver);
        //不能修改状态，用修改状态接口修改状态
        sysDriver.setStatus(null);
        this.updateById(sysDriver);
    }

    @Override
    public void add(SysDriverParam sysDriverParam) {
        checkIdCard(sysDriverParam, false);
        checkEmployeeCode(sysDriverParam, false);
        SysDriver sysDriver = new SysDriver();
        BeanUtil.copyProperties(sysDriverParam, sysDriver);
        //填充驾驶员其余信息
        sysDriver.setAge(IdcardUtil.getAgeByIdCard(sysDriver.getIdCard()));
        sysDriver.setStatus(0);
        this.save(sysDriver);
    }

    @Override
    public void changeStatus(SysDriverParam sysDriverParam) {
        SysDriver sysDriver = this.querySysDriver(sysDriverParam);
        Long driverIndex = sysDriver.getDriverIndex();
        Integer status = sysDriverParam.getStatus();
        //校验状态在不在枚举值里
        CommonStatusEnum.validateStatus(status);
        //更新枚举，更新只能更新未删除状态的
        LambdaUpdateWrapper<SysDriver> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysDriver::getDriverIndex, driverIndex)
                .and(i -> i.ne(SysDriver::getStatus, CommonStatusEnum.DELETED.getCode()))
                .set(SysDriver::getStatus, status);
        boolean update = this.update(updateWrapper);
        if (!update) {
            throw new ServiceException(StatusExceptionEnum.UPDATE_STATUS_ERROR);
        }
    }

    /**
     * 校验参数，检查是否存在相同身份证的驾驶员
     */
    private void checkIdCard(SysDriverParam sysDriverParam, boolean isExcludeSelf) {
        Long id = sysDriverParam.getDriverIndex();
        LambdaQueryWrapper<SysDriver> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDriver::getIdCard, sysDriverParam.getIdCard())
                .ne(SysDriver::getStatus, CommonStatusEnum.DELETED.getCode());
        //是否排除自己，如果是则查询条件排除自己id
        if (isExcludeSelf) {
            queryWrapper.ne(SysDriver::getDriverIndex, id);
        }
        int countByAccount = this.count(queryWrapper);
        //大于等于1个则表示重复
        if (countByAccount >= 1) {
            throw new ServiceException(SysDriverExceptionEnum.DRIVER_ID_CARD_REPEAT);
        }
    }

    /**
     * 校验参数，检查是否存在相同工号的驾驶员
     */
    private void checkEmployeeCode(SysDriverParam sysDriverParam, boolean isExcludeSelf) {
        Long id = sysDriverParam.getDriverIndex();
        LambdaQueryWrapper<SysDriver> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDriver::getEmployeeCode,sysDriverParam.getEmployeeCode())
                .ne(SysDriver::getStatus, CommonStatusEnum.DELETED.getCode());
        //是否排除自己，如果是则查询条件排除自己id
        if (isExcludeSelf) {
            queryWrapper.ne(SysDriver::getDriverIndex, id);
        }
        int countByAccount = this.count(queryWrapper);
        //大于等于1个则表示重复
        if (countByAccount >= 1) {
            throw new ServiceException(SysDriverExceptionEnum.DRIVER_CODE_REPEAT);
        }
    }



    /**
     * 获取驾驶员
     *
     */
    private SysDriver querySysDriver(SysDriverParam sysDriverParam) {
        SysDriver sysDriver = this.getById(sysDriverParam.getDriverIndex());
        if (ObjectUtil.isNull(sysDriver)) {
            throw new ServiceException(SysDriverExceptionEnum.DRIVER_NOT_EXIST);
        }
        return sysDriver;
    }
}
